/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import io.renren.SysUserEntityVo;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.bs.entity.BsDepartmentEntity;
import io.renren.modules.bs.entity.BsHospitalEntity;
import io.renren.modules.bs.service.BsDepartmentService;
import io.renren.modules.bs.service.BsHospitalService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.PasswordForm;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BsHospitalService hospitalService;

    @Autowired
    private BsDepartmentService departmentService;


    /**
     * 所有用户列表
     */
    @GetMapping("/list")

    public R list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
//		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
//		}
        PageUtils page = sysUserService.queryPage(params);

        List<SysUserEntity> list = (List<SysUserEntity>) page.getList();
        Set<Long> collect = new HashSet<>();
        Set<Long> departmentIdSet = new HashSet<>();
        for (SysUserEntity sysUserEntity : list) {
            Long hospitalId = sysUserEntity.getHospitalId();
            if (hospitalId != null) {
                collect.add(hospitalId);
            }
            Long departmentId = sysUserEntity.getDepartmentId();
            if (departmentId != null) {
                departmentIdSet.add(departmentId);
            }

        }

        Map<Long, BsHospitalEntity> hospitalMap = new HashMap<>();
        Map<Long, BsDepartmentEntity> departmentMap = new HashMap<>();
        if (collect.size() > 0) {

            Collection<BsHospitalEntity> bsHospitalEntities = hospitalService.listByIds(collect);
            hospitalMap = bsHospitalEntities.stream().collect(Collectors.toMap(BsHospitalEntity::getHospitalId, Function.identity()));
        }
        if (departmentIdSet.size() > 0) {

            Collection<BsDepartmentEntity> bsDepartmentEntities = departmentService.listByIds(departmentIdSet);
            departmentMap = bsDepartmentEntities.stream().collect(Collectors.toMap(BsDepartmentEntity::getDepartmentId, Function.identity()));
        }

        List<SysUserEntityVo> sysUserEntityVos = new ArrayList<>();
        for (SysUserEntity sysUserEntity : list) {
            SysUserEntityVo sysUserEntityVo = new SysUserEntityVo();
            BeanUtil.copyProperties(sysUserEntity, sysUserEntityVo);
            if (sysUserEntity.getHospitalId() != null) {
                BsHospitalEntity bsHospitalEntity = hospitalMap.get(sysUserEntity.getHospitalId());
                if (bsHospitalEntity != null) {
                    sysUserEntityVo.setHospitalName(bsHospitalEntity.getHospitalName());
                    if (sysUserEntity.getIsDepartmentManager() == 0) {
                        sysUserEntityVo.setUsername(sysUserEntityVo.getUsername() + "(" + bsHospitalEntity.getHospitalName() + ")");
                    }
                }
            }
            if (sysUserEntity.getDepartmentId() != null) {
                BsDepartmentEntity bsDepartmentEntity = departmentMap.get(sysUserEntity.getDepartmentId());
                if (bsDepartmentEntity != null) {
                    sysUserEntityVo.setDepartmentName(bsDepartmentEntity.getDepartmentName());
                }
            }
            sysUserEntityVos.add(sysUserEntityVo);
        }
        page.setList(sysUserEntityVos);
        return R.ok().put("page", page);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")

    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")

    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")

    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")

    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }
}
